package com.wowo.jdbc;

import lombok.Data;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Data
public class UserDao {
    JdbcTemplate jdbcTemplate;
    public void save(User user){
        jdbcTemplate.update("insert into users(name,age,birthday,pwd) values (?,?,?,?)",user.getName(),user.getAge(),user.getBirthday(),user.getPwd());
    }
    public void update(User user){
        jdbcTemplate.update("update users set name=?,age=?,birthday=?,pwd=? where id = ?",user.getName(),user.getAge(),user.getBirthday(),user.getPwd(),user.getId());

    }
    public void delete(int id){
        jdbcTemplate.update("delete from users where id = ?",id);
    }
    public User getUserById(int id){
        User user = jdbcTemplate.queryForObject("select * from users where id =?",new UserRomMap(),id);
        return user;
    }
    public List<User> getAll(){
        List<User> users = jdbcTemplate.query("select * from users",new UserRomMap());
        return users;
    }



    class UserRomMap implements RowMapper<User>{

        @Override
        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            //将查询的一条记录转换为User对象，并返回
            User user = new User();
            user.setId(rs.getInt("id"));
            user.setName(rs.getString("name"));
            user.setAge(rs.getInt("age"));
            user.setBirthday(rs.getDate("birthday"));
            user.setPwd(rs.getString("pwd"));

            return user;
        }
    }
}
